//
//  ClubSigninViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/11.
//

import UIKit

class ClubSigninViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("每日签到").color(.black).font(16.font_semiBold)
        .alignment(.center).end()
    private var bgImageView = c_make_ex(UIImageView.self)
        .image("Mine_signin_bg").mode(.scaleAspectFill).end()
    private var titleImageView = c_make_ex(UIImageView.self)
        .image("Mine_signin_title").mode(.scaleAspectFill).end()
    private var giftBgImageView = c_make_ex(UIImageView.self)
        .image("Mine_signin_bgGift").mode(.scaleAspectFill).end()
    private var contentBgView = c_make_ex(UIImageView.self)
        .image("Mine_signin_contentV").mode(.scaleAspectFill).end()
    private var storeButton = UIIconButton(style: .trailing(itemSpace: 0))
    private var rightImageView = c_make_ex(UIImageView.self)
        .image("Mine_signin_right").mode(.scaleAspectFill).end()
    private var leftImageView = c_make_ex(UIImageView.self)
        .image("Mine_signin_left").mode(.scaleAspectFill).end()
    private var myIntegralLabel = c_make_ex(UILabel.self)
        .color(.black).text("我的积分：").font(20.font_wide).end()
    private var integralValueLabel = c_make_ex(UILabel.self)
        .color("#FF7700").text("97").font(25.font_wide).end()
    private var subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").text("连续签到7天，本月剩余5次补签")
        .font(12.font_medium).end()
//    private var ruleButton = c_make_ex(UIButton.self)
//        .color("#7B7D80").text("积分规则").font(12.font_medium).end()
    private var signinButton = c_make_ex(UIButton.self)
        .image("Mine_signin_do").image("Mine_signin_done", state: .selected).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var ruleView = ClubMineSigninRuleView()
    
    private var dataSource: [ClubMySignDateModel]?
    private var isSign = false //是否加载过数据
    
    var updateBlock: (() -> Void)?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isSign {
            updateBlock?()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            bgImageView
            backButton
            titleLabel
            titleImageView
            giftBgImageView
            contentBgView.subviews{
                myIntegralLabel
                integralValueLabel
                subLabel
                storeButton
                collectionView
                rightImageView
                leftImageView
                signinButton
//                ruleButton
            }
            ruleView
        }
        
        bgImageView.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        titleImageView.leading(12.0.Scale).top(.navi_height + 4).width(145.0.Scale).height(56.0.Scale)
        giftBgImageView.top(30.0.Scale).trailing(0).width(213.0.Scale).height(237.0.Scale)
        contentBgView.leading(12.0.Scale).trailing(12.0.Scale).height(253.0.Scale)
        contentBgView.Top == titleImageView.Bottom + 15.0.Scale
        myIntegralLabel.top(12.0.Scale).leading(12.0.Scale)
        integralValueLabel.Leading == myIntegralLabel.Trailing
        integralValueLabel.CenterY == myIntegralLabel.CenterY
        subLabel.leading(12.0.Scale)
        subLabel.Top == myIntegralLabel.Bottom + 2
        storeButton.top(12.0.Scale).trailing(8.0.Scale).height(20.0.Scale).width(70.0.Scale)
        collectionView.leading(12.0.Scale).trailing(12.0.Scale).height(100)
        collectionView.Top == subLabel.Bottom + 20.0.Scale
        rightImageView.top(113.5.Scale).trailing(0).size(20.0.Scale)
        leftImageView.top(113.5.Scale).leading(0).size(20.0.Scale)
//        ruleButton.leading(35.0.Scale).trailing(35.0.Scale).height(15.0.Scale).bottom(9.0.Scale)
        signinButton.width(240.0.Scale).height(50.0.Scale).bottom(15.0.Scale).centerHorizontally()
        ruleView.leading(0).trailing(0).height(145.0.Scale)
        ruleView.Top == contentBgView.Bottom + 24.0.Scale
        
        storeButton.style { v in
            v.iconSize = CGSize(width: 20.0.Scale, height: 20.0.Scale)
            v.setImage("Mine_signin_next".toImage, for: .normal)
            v.setTitle("积分商城", for: .normal)
            v.setTitleColor("#FF7700".toColor, for: .normal)
            v.titleLabel?.font = 12.font_semiBold
            v.addTarget(self, action: #selector(clickStoreButton), for: .touchUpInside)
        }
        
        contentBgView.isUserInteractionEnabled = true
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 48.0.Scale, height: 98.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubMineSigninCell.self, forCellWithReuseIdentifier: ClubMineSigninCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        signinButton.addTarget(self, action: #selector(clickSigninButton), for: .touchUpInside)
    }
    
    
    private func loadData(){

        Task {
            let res = await network.request(.dailyInfo,type: ClubSignInModel.self)
            if res.isSuccess, let model = res.model {
                
                self.integralValueLabel.text = model.my?.charge_points
                if let count = model.my?.count, let serial = model.my?.serial {
                    self.subLabel.text = "你已累计签到" + count + "天，连续签到" + serial + "天"
                }
                if let list = model.list {
                    let today = Date().toString()
                    self.signinButton.isSelected = false
                    for i in 0..<list.count {
                        if list[i].time == today && list[i].sign == "1"{
                            self.signinButton.isSelected = true
                        }
                    }
                    if !isSign {
                        self.updateCollectionViewUI(list: list)
                    }
                    
                }
                self.dataSource = model.list
                self.collectionView.reloadData()
            }
        }
    }

    private func updateCollectionViewUI(list: [ClubMySignDateModel]){

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            
            let today = Date().toString()
            for i in 0..<list.count {
                if list[i].time == today {
                    self.collectionView.scrollToItem(at: IndexPath(item: i, section: 0), at: .left, animated: false)
                }
            }
        }
    }
}

//MARK: action
extension ClubSigninViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubMineSigninCell.description(), for: indexPath) as? ClubMineSigninCell else { return UICollectionViewCell() }
        cell.model = dataSource?[indexPath.row]
        return cell
    }
}

//MARK: action
extension ClubSigninViewController {
    
    @objc private func clickStoreButton(){
        
        self.navigationController?.pushViewController(ClubIntegralStoreViewController(), animated: true)
    }
    
    @objc private func clickSigninButton(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            if signinButton.isSelected {
                "您已签到".toast_warning
            }else{
                
                Task{
                    let res = await network.request(.dailyCheck)
                    if res.isSuccess {
                        "签到成功".toast_success
                        self.isSign = true
                        self.loadData()
                    }
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}
